package snooker.scoreboard.event;

import snooker.scoreboard.activity.R;
import android.app.Activity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class FinishActivityTouchListener implements OnTouchListener {

	//public static final int DIRECTION_NO_CHANGE = 0;
	public static final int DIRECTION_TO_RIGHT = 1;
	public static final int DIRECTION_TO_LEFT = 2;
	public static final int DIRECTION_TO_UP = 3;
	
	private static final int DIFF = 100;
	
	private Activity act;
	private int direction;
	private float downX = -1;
	private float downY = -1;
	
	public FinishActivityTouchListener(Activity act, int direction) {
		this.act = act;
		this.direction = direction;
	}
	
	public boolean onTouch(View v, MotionEvent event) {
		v.onTouchEvent(event);
		int action = event.getAction();
	    switch (action) { 
	    case (MotionEvent.ACTION_DOWN) : // Touch screen pressed
	    	downX = event.getX();
	    	downY = event.getY();
	        break; 
	    case (MotionEvent.ACTION_UP) : // Touch screen touch ended
	    	downX = -1;
	    	downY = -1;
	        break;
	    case (MotionEvent.ACTION_MOVE) : // Contact has moved across screen
	    	float x = event.getX();
			float y = event.getY();
			if (downX == -1 || downY == -1) {
				downX = x;
				downY = y;
			}
			if (direction == DIRECTION_TO_RIGHT && (x - downX) > DIFF) {
				downX = -1;
				act.finish();
				act.overridePendingTransition(
						R.anim.slide_in_from_left, 
						R.anim.slide_out_to_right);
			} else if (direction == DIRECTION_TO_LEFT && (downX - x) > DIFF) {
				downX = -1;
				act.finish();
				act.overridePendingTransition(
						R.anim.slide_in_from_right,
						R.anim.slide_out_to_left);
			} else if (direction == DIRECTION_TO_UP && (downY - y) > 60) {
					downY = -1;
					act.finish();
					act.overridePendingTransition(
							R.anim.slide_in_from_bottom, 
							R.anim.slide_out_to_top);
			}
	         break; 
	      case (MotionEvent.ACTION_CANCEL) : // Touch event cancelled
	         break;
	    }
	    
		return true;
	}
}
